<script lang="ts" setup>
import { ref } from "vue"
import { createApi, updateApi } from "@/api/Inventory"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { useRouter } from "vue-router"
import FormAddItem from "@/components/FormAddItem/index.vue"
import { TYPE_OPTIONS, REBATE_OPTIONS } from "./enums"
import dayjs from "dayjs"

defineOptions({
  // 命名当前组件
  name: "InventoryOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string

const loading = ref<boolean>(false)

const gotoList = () => {
  router.push("/inventory")
}
//#region 增
const DEFAULT_FORM_DATA = {
  id,
  product_code: "",
  weight: "",
  buying_price: "",
  box_gauge: "",
  product_quantity: "",
  brand_side: "",
  supplier: "",
  whether_to_rebate: "0",
  warehousing_time: dayjs().format("YYYY-MM-DD"),
  rebate_rate: "",
  cost_params: [],
  source: "0",
  payment_amount: ""
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<any>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<any> = {
  product_code: [{ required: true, trigger: "blur", message: "请输入商品编码" }],
  weight: [{ required: true, trigger: "blur", message: "请输入重量" }],
  buying_price: [{ required: true, trigger: "blur", message: "请输入进货价" }],
  payment_amount: [{ required: true, trigger: "blur", message: "请输入打款金额" }],
  box_gauge: [{ required: true, trigger: "blur", message: "请输入箱规" }],
  product_quantity: [{ required: true, trigger: "blur", message: "请输入商品数量" }],
  brand_side: [{ required: true, trigger: "blur", message: "请输入品牌方" }],
  supplier: [{ required: true, trigger: "blur", message: "请输入供货方" }],
  whether_to_rebate: [{ required: true, trigger: "blur", message: "请选择是否返利" }],
  warehousing_time: [{ required: true, trigger: "blur", message: "入库时间" }],
  rebate_rate: [{ required: true, trigger: "blur", message: "请输入返利比例" }],
  cost_params: [{ required: true, trigger: "blur", message: "请输入费用参数" }],
  source: [{ required: true, trigger: "blur", message: "请选择来源" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createApi : updateApi
    formData.value.cost_params = JSON.stringify(
      formData.value.cost_params.map((item: any) => {
        return {
          type: item.paramKey,
          cost: item.paramValue
        }
      })
    )
    formData.value.warehousing_time = dayjs(formData.value.warehousing_time).format("YYYY-MM-DD")
    api({
      data: [formData.value]
    })
      .then(() => {
        ElMessage.success("操作成功")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

//#region 查
// const getDetail = () => {
//   if (!id) {
//     return
//   }
//   getDetailApi(id)
//     .then(async ({ data }) => {
//       formData.value = data
//       formData.value.img_list = JSON.parse(formData.value.img_list)
//       formData.value.params = JSON.parse(formData.value.params)
//       formData.value.params_en = JSON.parse(formData.value.params_en)
//     })
//     .catch(() => {
//       formData.value = DEFAULT_FORM_DATA
//     })
// }
// onMounted(async () => {
//   getDetail()
// })
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ "录入库存" }}</h3>
        </div>
      </template>
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        label-position="right"
        style="max-width: 400px"
      >
        <el-form-item prop="product_code" label="商品编码">
          <el-input v-model="formData.product_code" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="weight" label="重量">
          <el-input v-model="formData.weight" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="buying_price" label="进货价">
          <el-input-number v-model="formData.buying_price" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="payment_amount" label="打款金额">
          <el-input-number v-model="formData.payment_amount" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="box_gauge" label="箱规">
          <el-input-number v-model="formData.box_gauge" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="product_quantity" label="商品数量">
          <el-input-number v-model="formData.product_quantity" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="brand_side" label="品牌方">
          <el-input v-model="formData.brand_side" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="supplier" label="供货方">
          <el-input v-model="formData.supplier" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="whether_to_rebate" label="是否返利">
          <el-select v-model="formData.whether_to_rebate" placeholder="请选择">
            <el-option v-for="item in REBATE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item prop="warehousing_time" label="入库时间">
          <el-date-picker v-model="formData.warehousing_time" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="rebate_rate" label="返利比例">
          <el-input-number v-model="formData.rebate_rate" placeholder="请输入" />
        </el-form-item>
        <form-add-item
          v-model="formData.cost_params"
          paramName="cost_params"
          param-key="类型"
          param-value="数值"
          addText="添加费用参数"
        />
        <el-form-item prop="name" label="来源">
          <el-select v-model="formData.source" placeholder="请选择">
            <el-option v-for="item in TYPE_OPTIONS" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
